<?php


class Apicart extends ApiBase {

	private $user_id;
	public function __construct(){
		parent::__construct();
		$this->user_id=$this->GetUser()['user_id'];
	}

	public function index(){
     $where['user_id']=$this->user_id;
     $list=$this->db->where($where)->select('id,goods_id,goods_num,sku')->get('cart')->result_array();
     foreach ($list as $k=>$v){
     	$list[$k]['image']=$this->GetImage($v['goods_id']);
		$list[$k]['goods_name']=$this->GetGoods($v['goods_id'])['goods_name'];
		$list[$k]['goods_price']=$this->getSkuPrice($v['sku']);
	 }
     $this->show($list);
	}

	public function GetGoods($goods_id){
		$where['goods_id']=$goods_id;
		$list=$this->db->where($where)->get('goods')->row_array();
		return $list;
	}

	public function GetImage($goods_id){
		$where['goods_id']=$goods_id;
		$list=$this->db->where($where)->get('goods_image')->row_array();
		return $this->GetImg($list['image_id']);
	}


	public function add(){
		$post=$this->input->post();
		$post['create_time']=time();
		$post['update_time']=time();
		$post['user_id']=$this->user_id;
		unset($post['token']);
        $where['user_id']=$this->user_id;
        $where['goods_id']=$post['goods_id'];
        $where['sku']=$post['sku'];
        $check=$this->db->where($where)->get('cart')->row_array();
        if ($check){
			$this->db->where('id',$check['id'])->set('goods_num','goods_num + 1',FALSE);
			$res= $this->db->update('cart');
		}else{
			$res=$this->db->insert('cart',$post);
		 }
		if ($res){
			$this->show(array('code'=>1,'msg'=>'添加成功'));
		}else{
			$this->show(array('code'=>0,'msg'=>'添加失败'));
		}
	}


	public function sub(){
		$post=$this->input->post();
		$where['user_id']=$this->user_id;
		$where['goods_id']=$post['goods_id'];
		$where['sku']=$post['sku'];
		$info=$this->db->where($where)->get('cart')->row_array();
		if ($info['goods_num']<=1){
			$this->show(array('code'=>1,'msg'=>'数量不能为0'));
		}else{
			$this->db->where($where);
			$this->db->set('goods_num','goods_num - 1',FALSE);
			$res= $this->db->update('cart');
			if ($res){
				$this->show(array('code'=>1,'msg'=>'减少成功'));
			}else{
				$this->show(array('code'=>0,'msg'=>'减少失败'));
			}
		}
	}


	public function del(){
		$post=$this->input->post();
		$where['user_id']=$this->user_id;
		$where['id']=(int)$post['id'];
		$this->db->where($where)->delete('cart');
		$res=$this->db->affected_rows();
		if ($res){
			$this->show(array('code'=>1,'msg'=>'删除成功'));
		}else{
			$this->show(array('code'=>0,'msg'=>'删除失败'));
		}

	}

}
